<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>部门管理</span>
      </div>
      <el-input
        v-model="id"
        placeholder="请输入要搜索的部门名称"
        class="ipt"
        @keyup.enter.native="search"
        @blur="offocus"
      ></el-input>
      <el-button type="primary" size="small" @click="search">查询</el-button>
      <el-button
        type="success"
        size="small"
        @click="addShow(true, '新建部门', null, 0)"
        >新建部门</el-button
      >
    </el-card>
    <el-tree
      :data="tableData"
      show-checkbox
      node-key="id"
      :searchText="searchText"
      :props="defaultProps"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <!-- <el-button type="success" size="mini" @click="details(data)">
            查询
          </el-button> -->
          <el-button
         type="primary" 
            size="mini"
            @click="addShow(true, '修改', data, 1)"
          >
            修改
          </el-button>
          <el-button  type="danger" size="mini" @click="delRow(data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      title="详情"
      :visible.sync="detastate"
      width="55%"
    >
      <span>
        <div class="details">
          <div class="item">
            <span style="display: inline-block; width: 120px; line-height: 50px"
              >负责人：</span
            ><span>{{ detail.user }}</span>
          </div>
          <div class="item">
            <span style="display: inline-block; width: 120px; line-height: 50px"
              >部门名称：</span
            ><span>{{ detail.name }}</span>
          </div>
          <div class="item">
            <span style="display: inline-block; width: 120px; line-height: 50px"
              >手机号：</span
            ><span>{{ detail.user_mobile }}</span>
          </div>
          <!-- <div class="item">
            <span style="display: inline-block; width: 120px; line-height: 50px"
              >openid:</span
            ><span>{{ detail.openid }}</span>
          </div> -->
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detastate = false">取 消</el-button>
        <el-button type="primary" @click="detastate = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="55%"
    >
      <span class="dialog">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="父级部门">
            <el-cascader
              :options="tableData"
              :props="defaultProps"
              clearable
              v-model="prine"
              @change="cascchange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="负责人" prop="user">
            <el-input v-model="form.user"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="user_mobile">
            <el-input v-model="form.user_mobile"></el-input>
          </el-form-item>
          <!-- <el-form-item label="openid" prop="openid">
            <el-input v-model="form.openid"></el-input>
          </el-form-item> -->
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="add(false)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
import {
  departmentlist,
  departmentdel,
  departmentshow,
  adddepartment,
  editdepartment,
} from "../api/section";
export default {
  data() {
    // 部门校验
    var validatename = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("部门不能为空"));
      }
      let reg = /^[\w\u4e00-\u9fa5]{2,8}$/;
      if (!reg.test(value)) {
        return callback(
          new Error("部门名称格式为中文数字字母下划线,长度为2-8位")
        );
      }
    };
    // 负责人校验
    var validateuser = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("管理负责人不能为空"));
      }
      let reg = /^[a-zA-Z\u4e00-\u9fa5]{2,6}$/;
      if (!reg.test(value)) {
        return callback(new Error("管理负责人名称格式为中文字母,长度为2-6位"));
      }
    };
    // 手机号校验
    var validatemobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      }
      let reg = /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/;
      if (!reg.test(value)) {
        return callback(
          new Error("请填写正确手机号,格式只能为数字,长度必须为11位")
        );
      }
    };
    // id校验
    var validateopenid = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("id不可为空"));
      }
      let reg = /^[0-9]{1,3}$/;
      if (!reg.test(value)) {
        return callback(new Error("id格式为数字,长度为1-3位"));
      }
    };
    return {
      rules: {
        name: [{ validator: validatename, trigger: "blur" }],
        user: [{ validator: validateuser, trigger: "blur" }],
        openid: [{ validator: validateopenid, trigger: "blur" }],
        user_mobile: [{ validator: validatemobile, trigger: "blur" }],
      },
      prine: "",
      total: 0,
      status: "",
      casc: [],
      form: {
        name: "",
        parent_id: "", //父级部门 （做成级联框选择）
        user: "",
        user_mobile: "",
        openid: "",
      },
      searchText: "",
      detail: {},
      defaultProps: {
        label: "name",
        checkStrictly: true,
        children: "son",
        value: "id",
        empty: false,
        multiple: false,
      },
      tableData: [],
      id: "",
      dialogVisible: false,
      detastate: false,
    };
  },

  mounted() {
    this.list();
  },

  methods: {
    // 详情
    async details(e) {
      console.log(e);
      const res = await departmentshow({ id: e.id });
      this.detastate = true;
      this.detail = res.data;
    },
    // 层级选择器chenge事件
    cascchange(e) {
      // console.log(e);
      let parent_id = e[e.length - 1];
      this.form.parent_id = parent_id;
    },
    // handleClose(done) {
    //   this.$confirm("确认关闭？")
    //     .then((_) => {
    //       done();
    //     })
    //     .catch((_) => {});
    // },
    close() {
      this.dialogVisible = false;
      this.form = {};
    },
    // 添加修改
    async addShow(show, title, data, flag) {
      // console.log(show, title, data, flag);
      this.dialogVisible = show;
      this.title = title;
      this.status = flag;
      if (flag) {
        this.updataid = data.id;
        const params = {
          name: data.name,
          parent_id: data.parent_id, //父级部门 （做成级联框选择）
          user: data.user,
          user_mobile: data.user_mobile,
          openid: data.openid,
        };
        this.form = _.cloneDeep(params);
      }
    },
    offocus() {
      if (this.id == "") {
        this.list();
      }
    },
    // 添加
    async add(show) {
      console.log(show);
      this.dialogVisible = show;
      const data = this.form;
      if (data.parent_id == "") {
        data.parent_id = 0;
      }
      if (this.status) {
        const params = {
          id: this.updataid,
          formdata: data,
        };
        const res = await editdepartment(params);
        this.list();
      } else {
        if (
          data.name == "" ||
          data.user == "" ||
          data.user_mobile == ""
        ) {
          this.$message.error("请确认表单数据是否填写正确");
          this.dialogVisible = true;
          return;
        }
        const res = await adddepartment(data);
console.log(res);
        if (res.code == "00000") {
          this.$refs.form.resetFields();
          this.$message.success("添加成功");
          this.list();
        }
      }
    },
    // 删除
    delRow(data) {
      const { id } = data;
      let ids = id;
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { code } = await departmentdel({ id: ids });
          // console.log(code);
          if (code == "00000") {
            this.$message.success("删除成功!");
            this.list();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 列表
    async list() {
      let res = await departmentlist({ id: this.id });
      const { code, data } = res.data;
      const casc = res.data;
      casc.filter((item) => {
        if (item.son.length != 0) {
          // console.log(item, 111);
        }
      });
      // console.log(res);
      if (res.code == "00000") {
        this.tableData = res.data;
        this.casc = res.data;
      }
    },
    // 查询
    search() {
      this.searchText = this.id;
    },
    filterNode(val, data) {
      console.log(val, data);
      if (!val) return true;
      return data.name.indexOf(val) !== -1;
    },
  },
  watch: {
    searchText(newval) {
      this.$refs.tree.filter(newval);
    },
  },
};
</script>

<style lang="less" >
.el-tree-node__content {
  padding: 10px 0;
}
.custom-tree-node {
  width: 100%;
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
}
</style>
<style lang="less" scoped>
.ipt {
  width: 20%;
  margin: 0 20px 0 0;
}
.el-form-item {
  .el-input {
    width: 70%;
  }
}
.el-card__body {
  padding: 10px 0px;
}
</style>